package com.xiejr.actuator.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiejr.actuator.enums.MessageStrategyEnum;
import com.xiejr.actuator.enums.RoleEnum;
import com.xiejr.actuator.exceptioin.SocketActuatorException;
import com.xiejr.actuator.service.SystemService;
import com.xiejr.actuator.socket.abstracts.CommonWebsocketHelper;
import com.xiejr.actuator.socket.model.Message;
import com.xiejr.actuator.util.WebsocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;

/**
 * @program: socket-actuator-spring-boot-starter
 * @description: 系统长连接
 * @author: xjr
 * @create: 2020-07-01 23:27
 **/
@ServerEndpoint("/system-socket")
@Component("system-socket")
@Slf4j
public class SystemWebsocket extends CommonWebsocketHelper {
    @Override
    public void open(Session session) throws SocketActuatorException {
        log.info("系统长连接已成功连上,ip为{}",this.ip);
    }

    @Override
    public void message(Session session,String message) throws SocketActuatorException {
        super.message(session,message);
        JSONObject messageJson= JSON.parseObject(message);
        MessageStrategyEnum messageStrategyEnum=MessageStrategyEnum.getBycode(messageJson.getString("strategy"));
        SystemService systemService= WebsocketUtils.applicationContext.getBean(SystemService.class);
        try {
            messageStrategyEnum.done(session,systemService,messageJson.getString("content"));
        }catch (Exception e){
            log.info("异常信息:{}",e.getMessage());
            throw new SocketActuatorException(e.getMessage());
        }
    }

    /**
     *
     * @param session 发生错误的会话
     * @param err  错误信息
     * @return void
     * @author xiejr
     * @creed: 处理错误情况
     * @date 2020/7/12 12:57
     */
    @Override
    public void error(Session session, Throwable err) throws Throwable {
        log.info("error occurred during the topic-socket connection!,reason is {}",err.getMessage());
        Message message=new Message("");
        message.setFrom(RoleEnum.SERVER.getCode());
        message.setTo(RoleEnum.CLIENT.getCode());
        message.setErrMsg(err.getMessage());
        message.setStatus("500");
        message.setSendTime(LocalDateTime.now().format(SECONDS_FORMATTER));
        session.getBasicRemote().sendText(JSON.toJSONString(message));
    }



}
